import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { Logger } from '../../utils/log4js';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp(); // 获取请求上下文
    const response = ctx.getResponse(); // 获取响应上下文中的 response对象
    const request = ctx.getRequest(); // 获取请求上下文
    const status = exception.getStatus(); // 获取异常状态码
    // console.log(status)
    // console.log(exception)
    // console.log(exception.getResponse())

    // 设置错误信息
    // const message = exception.message
    //   ? exception.message
    //   : `${status >= 500 ? 'Service Error' : 'Client Error'}`;

    const logFormat = ` <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    Request original url: ${request.originalUrl}
    Method: ${request.method}
    IP: ${request.ip}
    Status code: ${status}
    Response: ${exception.toString()} \n  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    `;
    Logger.info(logFormat);

    const message =
      (exception.getResponse() && (exception.getResponse() as any).message) ||
      (exception.message && exception.message) ||
      `${status >= 500 ? 'Service Error' : '参数错误'}`;

    const errorResponse = {
      data: {},
      message: message,
      code: status,
    };

    // // 设置返回的状态码， 请求头，发送错误信息
    // response.status(status);
    // response.header('Content-Type', 'application/json; charset=utf-8');
    // response.send(errorResponse);

    response.status(status).json(errorResponse);
  }
}
